const URIreg = /[-.+*]/g

export function getCookie (sKey) {
  let encode = encodeURIComponent(sKey).replace(URIreg, '\\$&')
  let reg = new RegExp(`(?:(?:^|.*;)\\s*${encode}\\s*\\=\\s*([^;]*).*$)|^.*$`)
  let cookie = document.cookie.replace(reg, '$1')
  return decodeURIComponent(cookie) || null
}

export function getCookieFromString (cookie, sKey) {
  let encode = encodeURIComponent(sKey).replace(URIreg, '\\$&')
  let reg = new RegExp(`(?:(?:^|.*;)\\s*${encode}\\s*\\=\\s*([^;]*).*$)|^.*$`)
  let newCookie = cookie.replace(reg, '$1')
  return decodeURIComponent(newCookie) || null
}

export function setCookie(name, value, expiredays = 30) {
  let exdate = new Date()
  exdate.setDate(exdate.getDate() + expiredays)
  document.cookie = `${name}=${value};expires=${exdate.toUTCString()};path=/`
}

export function removeCookie (name) {
  setCookie(name, '', -1)
}

export function removeAllCookie () {
  console.log('exec all')
  cookieKeys().forEach(name => { setCookie(name, '', -1) })
}

export function hasCookie (sKey) {
  let encode = encodeURIComponent(sKey).replace(URIreg, '\\$&')
  const hasReg = new RegExp('(?:^|;\\s*)' + encode + '\\s*\\=')
  return hasReg.test(document.cookie)
}

/* optional method: you can safely remove it! */
export function cookieKeys () {
  const reg = /((?:^|\s*;)[^=]+)(?=;|$)|^\s*|\s*(?:=[^;]*)?(?:\1|$)/g
  let aKeys = document.cookie.replace(reg, '').split(/\s*(?:=[^;]*)?;\s*/)
  for (let nIdx = 0; nIdx < aKeys.length; nIdx++) {
    aKeys[nIdx] = decodeURIComponent(aKeys[nIdx])
  }
  return aKeys
}
